<?php
/**
 * Created by PhpStorm.
 * User: 1
 * Date: 2017-03-06
 * Time: 11:39
 */

namespace app\src\customer\logic;


use app\src\base\helper\ExceptionHelper;
use app\src\base\helper\ValidateHelper;
use app\src\base\logic\BaseLogic;
use app\src\customer\model\CustomerInfo;
use app\src\user\logic\MemberConfigLogic;
use think\Db;
use think\exception\DbException;

class CustomerInfoLogic extends BaseLogic
{
    public function _init()
    {
        $this->setModel(new CustomerInfo());
    }



    public function addNew($info){
        $uid = $info['uid'];
        $to_uid = $info['to_uid'];
        $result = $this->getInfo(['uid'=>$uid,'to_uid'=>$to_uid]);
        if(ValidateHelper::legalArrayResult($result)){
            unset($info['uid']);
            unset($info['to_uid']);
            $result = $this->save(['uid'=>$uid,'to_uid'=>$to_uid],$info);
        }else{
            $result = (new MemberConfigLogic())->getInfo(['uid'=>$uid]);
            if($result['status']){
                $cfg = $result['info'];
                $alibaichuan_id = $cfg['alibaichuan_id'];
                $info['baichuan_id'] = $alibaichuan_id;
                $result = $this->add($info);
            }
        }

        return $result;
    }

    public function queryDetail($map,$page,$order){
        try{
            $query = Db::table("itboye_customer_info")->alias("c")
                ->field("c.to_uid,c.uid,c.msg,c.update_time,c.baichuan_id,cm.nickname")
                ->join(["common_member"=>"cm"],"cm.uid = c.uid","LEFT")
                ->order($order);

            $start = max(0,(intval($page['curpage'])-1)*intval($page['size']));
            $list = $query ->where($map) -> limit($start,$page['size']) -> select();

            $count = $this -> getModel() -> where($map) -> count();

            return $this -> apiReturnSuc(["count" => $count, "list" => $list]);
        }catch (DbException $ex){
            return $this -> apiReturnErr(ExceptionHelper::getErrorString($ex));
        }
    }
}